package com.eryos.android.cigarettecounter;

import java.util.Calendar;
import java.util.TimeZone;

import android.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.beans.SmokeTime;
import com.eryos.android.cigarettecounter.io.Preferences;
import com.eryos.android.cigarettecounter.widget.CigaretteCounterWidger;

/**
 * Project : CigaretteCounter Author : Olivier Combe URL : http://eryos.fr/CigaretteCounter/
 * 
 * Copyright(C)2011 - Olivier Combe
 * 
 * Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 * @version \$Revision.*\$
 * @author Olivier Combe
 */
public class CigaretteCounter extends RootActivity {

    /** *************** Static Variables. *************** **/
    private static final String NA_LABEL = "NA";

    /** *************** Instance Variables. *************** **/
    private float cigarettePrice = 0;
    private int dailyCount = 0;
    private double weekAvg = 0;
    private double monthAvg = 0;
    private SmokeTime last = new SmokeTime();
    // private SmokeTime delay = new SmokeTime();
    private String cigarette = "";
    private String day = "";
    private String hour = "";
    private String days = "";
    private String minute = "";
    private String minutes = "";
    private int nbCigarettes = 1;

    /** *************** UI Elements. *************** **/
    private TextView dailyCountValue;
    private TextView lastCigValue;
    private TextView avgWeekValue;
    private TextView avgMonthValue;

    private Button addButton;
    private Button addPastButton;
    private Button showWeeklyStatButton;
    private Button showMonthlyStatButton;

    private Preferences pref;

    /** *************** *********** *************** **/

    /**
     * init Values(not UI)for this activiry from DB / Network / etc.
     */
    @Override
    public void initValues() {
        /* Retrieve the Cigarette price */
        pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
        pref.readParamFromFile();
        cigarettePrice = pref.getCigarettePrice();

        /* Refresh the UI with DB values */
        retieveDataFromDB();
    }

    /**
     * 
     * Method used to refresh the Daily Counter.
     */
    public void showDailyCount() {
        Log.d(getLogTag(), "showDailyCount");
        dailyCountValue.setText(dailyCount + " " + cigarette);
    }

    /**
     * Method used to refresh the Weekly Average.
     */
    public void showWeeklyAverage() {
        Log.d(getLogTag(), "showWeeklyAverage");
        final String weekValueLabel = weekAvg + " " + cigarette + " / " + day;
        if (weekAvg <= 0) {
            avgWeekValue.setText(NA_LABEL);
        } else {
            avgWeekValue.setText(weekValueLabel);
        }
    }

    /**
     * Method used to refresh the Monthly Average.
     */
    public void showMonthlyAverage() {
        Log.d(getLogTag(), "showMonthlyAverage");
        String monthValueLabel = monthAvg + " " + cigarette + " / " + day;
        if (monthAvg <= 0) {
            avgMonthValue.setText(NA_LABEL);
        } else {
            avgMonthValue.setText(monthValueLabel);
        }
    }

    /**
     * Method used to refresh the Delay since Last Cigarette.
     */
    public void showDelaySinceLast() {
        Log.d(getLogTag(), "showDelaySinceLast");
        String lastLabel = "";
        Log.d(getLogTag(), "Last Cigarettes : " + last);
        if (last.getDay() > 0) {
            lastLabel = last.getDay() + " " + days + " " + last.getHour() + " " + hour;
        } else {
            if (last.getHour() == 0) {
                lastLabel = last.getMinute() + " " + minute;
            } else {
                lastLabel = last.getHour() + " " + hour + " " + last.getMinute() + " " + minute + "("
                        + last.getTotalMinutes() + " " + minutes + ")";
            }
        }

        if (last != null && last.getTotalMinutes() < 0) {
            lastCigValue.setText(NA_LABEL);
        } else {
            lastCigValue.setText(lastLabel);
        }
    }

    /**
     * Method used to refresh the Average delay between 2 cigarettes.
     */
    public void showAverageDelay() {
        Log.d(getLogTag(), "showAverageDelay");
    }

    /**
     * Init all UI elements.
     */
    @Override
    public void initUI() {
        setContentView(R.layout.main);
        Log.d(getLogTag(), "initUI");

        addButton = (Button) findViewById(R.id.home_add_cigarette_button);
        addPastButton = (Button) findViewById(R.id.home_add_past_cigarette_button);
        showWeeklyStatButton = (Button) findViewById(R.id.home_button_history_week);
        showMonthlyStatButton = (Button) findViewById(R.id.home_button_history_month);

        dailyCountValue = (TextView) findViewById(R.id.home_daily_count_value_field);
        lastCigValue = (TextView) findViewById(R.id.home_delay_last_value_field);
        avgWeekValue = (TextView) findViewById(R.id.home_week_average_value_field);
        avgMonthValue = (TextView) findViewById(R.id.home_month_average_value_field);

        cigarette = getResources().getString(R.string.cigarette);
        day = getResources().getString(R.string.day);
        days = getResources().getString(R.string.days);
        hour = getResources().getString(R.string.hour);
        minute = getResources().getString(R.string.minute);
        minutes = getResources().getString(R.string.minutes);
    }

    /**
     * Method used to update the UI after called to initValues().
     */
    @Override
    public void updateUI() {
        Log.d(getLogTag(), "updateUI");

        showDailyCount();

        showDelaySinceLast();

        showAverageDelay();

        showWeeklyAverage();

        showMonthlyAverage();

    }

    /**
     * Method used to show/refresh all values on Main View.
     */
    public void retieveDataFromDB() {
        Log.d(getLogTag(), "retrieveDataFromDB");

        dailyCount = db.getDailyAdapter().getDailyCount();

        weekAvg = db.getWeeklyAdapter().getAverage();

        monthAvg = db.getMonthlyAdapter().getAverage();

        last = db.getDailyAdapter().getDelaySinceLast();
    }

    /**
     * Method called when a click is made on the " +1 button".
     */
    public void clickAddButton() {
        Log.d(getLogTag(), "Click on Add Button");

        /* Insert current TimeStamp */
        db.insertCurrentTimestamp("", cigarettePrice);

        /* Retrieve data from DB */
        retieveDataFromDB();

        /* Update UI values */
        updateUI();

        // Update widget(s)
        CigaretteCounterWidger.updateAllWidgets(this.getApplicationContext());

        /* Display a quick message */
        Toast.makeText(this, R.string.home_insert_OK, Toast.LENGTH_SHORT).show();
    }

    /**
     * Method called when a click is made on the "Add Past Cigarette" button.
     */
    private void clickAddPastButton() {
        Log.d(getLogTag(), "Click on Add Past Button");

        /* Init Dialog box */
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.show();
        dialog.setContentView(R.layout.datetime_dialog);

        /* Init Components */
        final Button addPastCigButton = (Button) dialog.findViewById(R.id.dialog_add_button);
        final Button cancelButton = (Button) dialog.findViewById(R.id.dialog_cancel_button);
        final DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.dialog_datePicker);
        final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.dialog_timePicker);
        timePicker.setIs24HourView(true);

        final Spinner boxSpinner = (Spinner) dialog.findViewById(R.id.dialog_nb_cigarette);
        final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(CigaretteCounter.this,
                R.array.cigarettes_array, android.R.layout.simple_spinner_item);

        /* Define ListBox Values */
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        boxSpinner.setAdapter(adapter);
        boxSpinner.setSelection(0);

        /* Retrieve number of cigarettes selected */
        boxSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(final AdapterView<?> parent, final View view, final int pos, final long id) {
                try {
                    String res = parent.getItemAtPosition(pos).toString();
                    nbCigarettes = Integer.valueOf(res.substring(1, 2));
                } catch (NumberFormatException e) {
                    nbCigarettes = 1;
                }
            }

            @Override
            public void onNothingSelected(final AdapterView<?> parent) {
            }
        });

        /* Click Handler for Valid Button */
        addPastCigButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {
                showWaitingMessage();
                Log.d(getLogTag(), "Click Monthly Stats Button");

                /* Retrieve Date & Time from Pickers */
                final int selectedHour = timePicker.getCurrentHour();
                final int selectedMinute = timePicker.getCurrentMinute();

                final int selectedDay = datePicker.getDayOfMonth();
                final int selectedMonth = datePicker.getMonth();
                final int selectedYear = datePicker.getYear();

                Calendar c = Calendar.getInstance();
                c.setTimeZone(TimeZone.getDefault());
                c.set(Calendar.YEAR, selectedYear);
                c.set(Calendar.MONTH, selectedMonth);
                c.set(Calendar.DAY_OF_MONTH, selectedDay);

                c.set(Calendar.HOUR_OF_DAY, selectedHour);
                c.set(Calendar.MINUTE, selectedMinute);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);

                long timestamp = c.getTimeInMillis() / 1000;

                /* Insert current TimeStamp */
                for (int i = 0; i < nbCigarettes; i++) {
                    db.insertTimestamp(cigarettePrice, timestamp, "Past Data");
                }

                /* Retrieve data from DB */
                retieveDataFromDB();

                /* Update UI values */
                updateUI();

                // Update widget(s)
                CigaretteCounterWidger.updateAllWidgets(CigaretteCounter.this.getApplicationContext());

                /* Display a quick message */
                dialog.dismiss();
                hideWaitingMessage(getResources().getString(R.string.home_insert_X_OK, nbCigarettes + ""));
            }
        });

        /* Click Handler for Cancel Button */
        cancelButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * Method used to defined all UI handlers.
     */
    @Override
    public void initHandlers() {
        Log.d(getLogTag(), "initHandlers");
        // Listeners & Handlers
        addButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {
                Log.d(getLogTag(), "Click Add Button");
                clickAddButton();
            }
        });

        addPastButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {
                Log.d(getLogTag(), "Click Add Past Button");
                clickAddPastButton();
            }
        });

        showWeeklyStatButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {
                Log.d(getLogTag(), "Click Weekly Stats Button");
                showView(VIEW.WEEKLY);
            }
        });

        showMonthlyStatButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(final View view) {
                Log.d(getLogTag(), "Click Monthly Stats Button");
                showView(VIEW.MONTHLY);
            }
        });
    }

}
